package com.hcj.admin.controller;

import com.hcj.util.resultUtil.Json;
import com.hcj.util.resultUtil.JsonResult;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.cache.Cache;
import org.apache.shiro.cache.CacheManager;
import org.apache.shiro.cache.ehcache.EhCacheManager;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.Set;

/**
 * @Author: HuangChangjin 2017-10-23 18:57
 * @Description:
 */
@Controller
@RequestMapping
public class LoginController {
    private Logger logger = LoggerFactory.getLogger(LoginController.class);
    @Autowired
    private EhCacheManager ehCacheManager;

    @RequestMapping(value = "/login", method = RequestMethod.POST)
    @ResponseBody
    public Json login(
        @RequestParam(value = "userName", required = true) String userName,
        @RequestParam(value = "password", required = true) String password,
        @RequestParam(value = "rememberMe", required = true, defaultValue = "false") boolean rememberMe
    ) {
        logger.error("\nuserName={}\npassword={}\nrememberMe={}" , userName , password , rememberMe);
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken(userName , password , rememberMe);
        if (!subject.isAuthenticated()) {
            try {
                subject.login(token);
            } catch (UnknownAccountException uae) {
                logger.info("There is no user with username of " + token.getPrincipal());
                return JsonResult.json("There is no user with username of " + token.getPrincipal());
            } catch (IncorrectCredentialsException ice) {
                logger.info("Password for account " + token.getPrincipal() + " was incorrect!");
                return JsonResult.json("Password for account " + token.getPrincipal() + " was incorrect!");
            } catch (ExcessiveAttemptsException ee){
                logger.info("Password for account: " + token.getPrincipal() + " tried to login more than 5 times in period,please try it after 10 secends");
                return JsonResult.json("Password for account: " + token.getPrincipal() + " tried to login more than 5 times in period,please try it after 10 secends");
            } catch (LockedAccountException lae) {
                logger.info("The account for username " + token.getPrincipal() + " is locked.  " +
                        "Please contact your administrator to unlock it.");
                return JsonResult.json("The account for username " + token.getPrincipal() + " is locked.  " +
                        "Please contact your administrator to unlock it.");
            } catch (AccountException ae){
                logger.info(ae.getMessage());
                return JsonResult.json("账号异常"+ae.getMessage());
            } catch (AuthenticationException e) {
                logger.info(e.getMessage());
                //rediect.addFlashAttribute("errorText", "您的账号或密码输入错误!");
                return JsonResult.json("您的账号或密码输入错误");
            } catch (Exception e){
                logger.info(e.getMessage());
                return JsonResult.json("未知错误");
            }
        }
        logger.error("subject.isRemembered();{}",subject.isRemembered());
        return JsonResult.jsonSuccess("登入成功");
    }

    @RequestMapping(value = {"/loginUI"})
    public String loginUI() {
        return "login";
    }

    @RequestMapping("/404")
    public String code404() {
        return "404";
    }
    @RequestMapping("/403")
    public String code403() {
        return "403";
    }
    @RequestMapping("/500")
    public String code500() {
        return "500";
    }

    @RequestMapping("/logout")
    @ResponseBody
    public Json logout(String q) {
        logger.info("q="+q);
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        return JsonResult.jsonSuccess("登出成功");
    }

    // TODO 测试缓存的获取
    @GetMapping("cache")
    @ResponseBody
    public Json cacheTest(String username){
        CacheManager cacheManager = ehCacheManager;
        Cache<String,Object> cache = cacheManager.getCache("cacheName");
        cache.put("hi","hello world");
        cache.put("hi","hello world1");
        cache.put("hi1","hello world1");
        logger.error("\n缓存={}",cache);
        Set<String> element = null;
        element = cache.keys();
        for(String object :element){
            logger.error("\n元素={}",cache.get(object));
        }
        return  JsonResult.jsonSuccess("element="+element+"\ncacahe="+cache);
    }
}
